use crate::model::Api;
use common::util::capitalize_first_letter;

pub fn generate_function(api: &Api) -> Result<String, Box<dyn std::error::Error>> {
    Ok(format!(
        r#"
export const {} = apiFactory({{
  path: "{}",
  method: "{}",
}})
export const use{} = () => useApi({});
"#,
        &api.name,
        api.path,
        api.method.to_uppercase(),
        capitalize_first_letter(&api.name),
        &api.name
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_function() -> Result<(), Box<dyn std::error::Error>> {
        let api = Api {
            name: "getUser".to_string(),
            method: "GET".to_string(),
            path: "/user/{id}".to_string(),
            request: serde_json::json!({
                "type": "object",
                "properties": {
                    "id": { "type": "string" }
                },
            }),
            response: serde_json::json!({
                "type": "object",
                "properties": {
                    "id": { "type": "string" },
                    "name": { "type": "string" }
                },
            }),
        };
        assert_eq!(
            generate_function(&api).expect("generate_function error"),
            r#"
export const getUser = apiFactory({
  path: "/user/{id}",
  method: "GET",
})
export const useGetUser = () => useApi(getUser);
"#
        );
        Ok(())
    }
}
